﻿using MySql.Data.MySqlClient;
using NB.MGJ.Common.Utility;
using NB.MGJ.FrameWork;
using NB.MGJ.Model;
using NB.MGJ.Model.CodeManage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using L.EntityFramework;
namespace NB.MGJ.Service.Product
{
    public partial class ProductBatchService : BaseService
    {
        private BaseRepository _baseRepository = new BaseRepository();
        private ManagerService _ManagerService = new ManagerService();

         private BaseRepository<L.EntityModel.EntityContext> baseRepository2;
         public ProductBatchService()
        {
            baseRepository2 = CreateBaseRepository<L.EntityModel.EntityContext>();
           
        }

        //微信小程序批次添加

        #region 增


        public int AddProductBatch(L.EntityModel.Product_Batch model)
        {
            try
            {
                model.ChangeDate = DateTime.Now;
                int rulset = baseRepository2.Insert<L.EntityModel.Product_Batch>(model);
                return rulset;
            }catch(Exception ex){

                throw ex;
            
            }

        }
        //微信小程序批次下拉框
        
         public IEnumerable<SelectItem> GetListByEnterId(int EID)
         {
             string sql = "SELECT ID,BATCHNAME FROM PRODUCT_BATCH WHERE ENTERPRISEID=" + EID;
             return _baseRepository.ExecuteSqlCollection<Product_Batch>(sql).Select(p =>
             {
                 return new SelectItem
                 {
                     Code = p.Id,
                     Name = p.BatchName
                 };
             });

         }
         #endregion


        #region 删
        public int DelBatchService(int id)
        {
            Product_Batch pb = new Product_Batch();
            pb.ViewDel = 1;
            pb.Id = id;
            pb.ChangeDate = DateTime.Now;
            pb.CommonId = 1;
            return _baseRepository.Update<Product_Batch>(pb);
        }


        #endregion


        #region 改

        public int Updbatch(Product_Batch model)
        {
            model.ChangeDate = DateTime.Now;
            return _baseRepository.Update<Product_Batch>(model);
        }

        #endregion


        #region 查

        public Product_Batch GetModelById(int id)
        {
            string sql = "select * from Product_Batch where ID=" + id;
            var result = _baseRepository.ExecuteText<Product_Batch>(sql);
            return result;

        }


        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="Psearch">查询条件</param>
        /// <returns></returns>
        public PagedList<Product_Batch> GetPageLists(ref PagerModel page, DetailSearch Smodel, LogOnUserModel user)
        {

            page.FldName = @" * ";
            page.TblName = @"(SELECT Product_Batch.ID,Product_Batch.ViewDel,Product_Batch.BatchName,Product_Product.ProductName,Product_Product.ImageUrl1,Organization_Enterprise.EnterpriseName,Organization_Enterprise.ID as EID,Product_Batch.ProductId,Product_Batch.MaterialId,Product_Batch.Version,Product_Batch.ChangeDate
                      FROM         Product_Batch left JOIN
                      Product_Product ON Product_Batch.ProductId = Product_Product.ID left JOIN
                      Origins_Material ON Product_Batch.MaterialId = Origins_Material.MaterialId left JOIN
                      Organization_Enterprise ON Product_Batch.EnterpriseId = Organization_Enterprise.ID) z";

            string StrCondition =" 1=1 ";
            if (Smodel.BatchName != null)
            {
                StrCondition += "  and (BatchName like '%" + Smodel.BatchName + "%')";
            }
            if (Smodel.EnterpriseName != null)
            {
                StrCondition += "  and (EnterpriseName like '%" + Smodel.EnterpriseName + "%')";
            }
            if (Smodel.ProductName != null)
            {
                StrCondition += "  and (ProductName like '%" + Smodel.ProductName + "%')";
            }
            if (Smodel.StartDate != "" && Smodel.StartDate != null)
            {
                StrCondition += " and  (left(ChangeDate,10) >= '" + Smodel.StartDate + "')";
            }
            if (Smodel.EndDate != "" && Smodel.EndDate != null)
            {
                StrCondition += " and  (left(ChangeDate,10) <= '" + Smodel.EndDate + "')";
            }

            StrCondition+= " and  ViewDel=0 and EID=" + user.EnterpriseId;
            page.StrCondition = StrCondition;

            if (string.IsNullOrEmpty(page.FldSort) || page.FldSort == "")
                page.FldSort = "ID  desc ";

            MySqlParameter[] parameters = _baseRepository.SqParameterRefactor(ref page);
            IEnumerable<Product_Batch> resultList = _baseRepository.ExecuteStoredProcedureCollection<Product_Batch>("Common_PageList", parameters);
            return new PagedList<Product_Batch>(resultList, page.Page, page.PageSize, 1, Convert.ToInt32(parameters[6].Value));

        }
        //小程序
        public PagedList<Product_Batch> GetPageList(ref PagerModel page,string Psearch)
        {

            page.FldName = @" * ";
            page.TblName = @"(SELECT Product_Batch.ID,Product_Batch.ViewDel,product_batch.TempletId,
                      Origins_Node.NodeName TempletName,Product_Batch.BatchName,Product_Product.ProductName,Organization_Enterprise.EnterpriseName,Organization_Enterprise.ID as EID,Product_Batch.ProductId,REPLACE(ImageUrl1,'http://','https://') as ImageUrl1,Product_Batch.MaterialId,Product_Batch.Version,Product_Batch.ChangeDate
                      FROM         Product_Batch left JOIN
                      Product_Product ON Product_Batch.ProductId = Product_Product.ID left JOIN
                      Origins_Material ON Product_Batch.MaterialId = Origins_Material.MaterialId left JOIN
                      Organization_Enterprise ON Product_Batch.EnterpriseId = Organization_Enterprise.ID
                      LEFT JOIN Origins_Node ON product_batch.TempletId = origins_node.ID
                      ) z";


            if (string.IsNullOrEmpty(page.FldSort) || page.FldSort == "")
                page.FldSort = "ID  desc ";

            MySqlParameter[] parameters = _baseRepository.SqParameterRefactor(ref page);
            IEnumerable<Product_Batch> resultList = _baseRepository.ExecuteStoredProcedureCollection<Product_Batch>("Common_PageList", parameters);
            return new PagedList<Product_Batch>(resultList, page.Page, page.PageSize, 1, Convert.ToInt32(parameters[6].Value));

        }

        #endregion


        #region 其他


        public List<Product_Batch> GetListByEID(int EID)
        {
            string sql="";
            if (EID != 1)
            {
                var sonEnterprise = _ManagerService.GetSonEnterpriseStrArray(EID);
                var searchSql = " AND ViewDel=0 and  EnterpriseId in (" + sonEnterprise + ")";
                sql = "select * from Product_Batch where 1=1 " + searchSql;
            }
            else
            {
                sql = "select * from Product_Batch where EnterpriseId=1 " ;
            }
           
            var result = _baseRepository.ExecuteSqlCollection<Product_Batch>(sql).ToList();
            return result;
        }




        public List<SelectListItem> GetBatchSelectList(int batchId, int eid)
        {
            List<Product_Batch> result = GetListByEID(eid);
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem() { Text = "--请选择--", Value = "" });
           
            for (int i = 0; i < result.Count; i++)
            {
                SelectListItem item = new SelectListItem()
                {
                    Text = result[i].BatchName,
                    Value = result[i].Id.ToString()
                };
                if (batchId == result[i].Id)
                {

                    item.Selected = true;
                }
                items.Add(item);
            }
            return items;
        }


        public IEnumerable<Product_Batch> GetAllBatch(string key)
        {
            var resule = "SELECT Product_Batch.ID,Product_Batch.ViewDel,Product_Batch.BatchName, Product_Product.ProductName, Organization_Enterprise.EnterpriseName,Product_Batch.ChangeDate  FROM Product_Batch left JOIN Product_Product ON Product_Batch.ProductId =Product_Product.ID left JOIN Origins_Material ON Product_Batch.MaterialId = Origins_Material.MaterialId left JOIN Organization_Enterprise ON Product_Batch.EnterpriseId = Organization_Enterprise.ID where Product_Batch.ViewDel=0";
            if (!string.IsNullOrWhiteSpace(key))
            {
                resule += " and Product_Batch.ID in("+key+")";
            }
            return _baseRepository.ExecuteSqlCollection<Product_Batch>(resule);
        }







        #endregion






        #region 产品手机端



        //微信小程序产品下拉框
        public IEnumerable<SelectItem> GetproductList()
        {
            string sql = " select ID,ProductName from Product_Product where ProductName is not null";
            return _baseRepository.ExecuteSqlCollection<Product_Product>(sql).Select(p =>
            {
                return new SelectItem
                {
                    Code = p.Id,
                    Name = p.ProductName
                };
            });
        }

        public void UpdateProductBatch(Product_Batch model)
        {
            var _set = string.Empty;

            _set += string.Format(" ChangeDate='{0}',ChangeLoginName='{1}',ChangeLoginID='{2}',`Version`={3}", DateTime.Now, model.ChangeLoginName, model.ChangeLoginID,model.Version);

            if (!string.IsNullOrWhiteSpace(model.BatchName))
            {
                _set += string.Format(",BatchName='{0}'", model.BatchName);
            }
            if (model.ProductId.HasValue && !string.IsNullOrWhiteSpace(_set))
            {
                _set += string.Format(",ProductId='{0}'", model.ProductId.Value);
            }
            if (!string.IsNullOrWhiteSpace(_set))
            {
                _set += string.Format(",Remark='{0}'", model.Remark);
            }
            _baseRepository.ExecuteSql<int>(string.Format("UPDATE product_batch SET {0} WHERE ID = {1}", _set, model.Id));
        }

      
        public IEnumerable<SelectItem> GetProductNameList(int enterprseId, int? typeId)
        {
            string sql = "SELECT ID `Code`,ProductName `Name` FROM Product_Product WHERE ViewDel=0 And EnterpriseId=" + enterprseId;
            if (typeId.HasValue)
            {
                sql += string.Format(" OR TypeId = {0}  ", typeId.Value);
            }
            return _baseRepository.ExecuteSqlCollection<SelectItem>(sql);
           
        }

        public IEnumerable<SelectItem> GetEnterpriseNameList(int enterpriseId)
        {
            string sql = " select ID `Code`,EnterpriseName `Name` from Organization_Enterprise where Id=" + enterpriseId;
            return _baseRepository.ExecuteSqlCollection<SelectItem>(sql);
        }


        public Product_Product GetproductModel(int Id)
        {
            string sql = " select ID,ProductName from Product_Product where Id=" + Id;
            return _baseRepository.ExecuteText<Product_Product>(sql);
            
        }

        public Product_Product GetproductByBat(int batchId)
        {
            string sql = " select b.ID,b.ProductName,a.BatchName from product_batch a left join product_product b on a.productId=b.ID where a.id=" + batchId;
            return _baseRepository.ExecuteText<Product_Product>(sql);

        }
        #endregion
        
        //扫码记录
        public PagedList<ScanCodeHistory> GetCodePageList(ref PagerModel page)
        {

            page.FldName = @" * ";
            page.TblName = "scancodehistory";
            if (string.IsNullOrEmpty(page.FldSort) || page.FldSort == "")
                page.FldSort = "ScanDate  desc ";
            MySqlParameter[] parameters = _baseRepository.SqParameterRefactor(ref page);
            IEnumerable<ScanCodeHistory> resultList = _baseRepository.ExecuteStoredProcedureCollection<ScanCodeHistory>("Common_PageList", parameters);
            return new PagedList<ScanCodeHistory>(resultList, page.Page, page.PageSize, 1, Convert.ToInt32(parameters[6].Value));

        }



    }
}
